<script setup lang="js">

import { ref, onMounted } from 'vue'
import {  getSalePageProduct,buyProduct, addToCarts, getProductHeaderImg } from '@/api'
import { useRoute }  from 'vue-router';
import { useUserStore } from '@/stores'
import { success,error, getSize } from '@/utils'

import  GoodsDetailsView  from '@/layouts/modules/goods/GoodsDetailsView.vue'
import GoodsComment from '@/layouts/modules/goods/GoodsComment.vue'
import AfterSaleProtection from '@/layouts/modules/goods/AfterSaleProtection.vue'
import SpecificationView from '@/layouts/modules/goods/SpecificationView.vue'
import ShopGoodGoods from '@/layouts/modules/goods/ShopGoodGoods.vue'
import { goods_page_bottom } from '@/utils/modules/CommonConstant'


const activeIndex = ref("1")

//收货地址
const selectAddress = ref('')

//用于决定显示商品购买时的各种条件的变量
const product_type = ref('')

// 商品尺寸
const selectSize = ref('')

//商品颜色
const select_color = ref('');

// 商品数量
const product_number = ref(1);

// 是否加入购物车
const shipping_cart = ref(false)


//购买确认对话框显示变量
const dialogVisible = ref(false)

// 商品信息
const product = ref({
  id:'',
  name:'',
  price:'',
  type:''
})


// 用户的所有收货地址
const address = ref([
  {
    id:1,
    address: '广东省广州市海珠区海珠街道海珠路海珠路1号海珠小区海珠路1号'
  },
  {
    id:2,
    address: '广东省广州市海珠区海珠街道海珠路海珠路25号'
  },
  ])

// 所有尺码
const sizes = new Map()

// 所有颜色
const colors = ref([])

// 商品样板图片
//商品各种图片
const headerImgs = ref([])


onMounted(async ()=>{
  await initProduct()
  activeIndex.value = '1'
  await getProductHeaderImgs()
})

const initProduct = async () => {
  activeIndex.value = '0'
  product.value.id = useRoute().query.name + ''
  product_type.value = useRoute().query.type + ''
  getSalePageProduct(product.value.id).then(({ data })=>{
    if(data === ""|| data === " " ){
      return
    }
    product.value.name = data.name
    product.value.price = data.price
    product.value.type = data.classId + ''

    const list = data.productStoreList

    //获取该商品的所有颜色
    const color_set = new Set();
    list.forEach( item =>{
      color_set.add(item.color)
    })
    colors.value = Array.from(color_set.values())
    //初始化选中的颜色
    select_color.value = colors.value[0]

    //获取该商品的所有尺码
    colors.value.forEach(color=>{
      const size_set = new Set();

      list.forEach( item =>{
        const details = new Map();
        if(item.color === color){
          details.set("size", item.size)
          details.set("stock", item.stock)
          size_set.add(details)
        }
      })
      if(size_set.size !== 0){
        sizes.set(color, Array.from(size_set.values()))
      }
    })
  })
}

const getProductHeaderImgs = ()=>{
  getProductHeaderImg(product.value.id).then(({data})=>{
    if(data.length===0 || data === " "){
      error('商品信息获取失败')
      return
    }
    data.forEach(item=>{
      headerImgs.value.push(item.url+'/'+item.name)
    })
  })
}



const productNumberChange = (value)=>{
  product_number.value = value
}

//加入购物车的函数
const addToCart = async () => {
  console.log(selectSize.value)
  await addToCarts({
       cid: useUserStore().uid,
       ppid:product.value.id,
       num:product_number.value,
       color:select_color.value,
       size:selectSize.value,
       price:product.value.price,
       address:selectAddress.value
  }).then(({data})=>{
    if(data === " " || data === ""){
      return
    }
    if (data){
      success("加入购物车成功")
      shipping_cart.value = true
    }else {
      error("加入购物车失败,可能已经加入购物车了")
    }
  },(err)=>{
    error("加入购物车失败")
  })


}

//购买商品
const buyNow = () => {
  dialogVisible.value = false
  buyProduct({
    customId:useUserStore().uid,
    productId:product.value.id,
    shippingAddress:selectAddress.value,
    number:product_number.value,
    price:product.value.price,
    color:select_color.value,
    size:selectSize.value
  }).then(({data})=>{
    if(data === ""){
      return
    }
    if(data){
      success("购买成功")
    }else {
      error("购买失败")
    }
  },(err) =>{
    error("购买失败")
  })
}

const handleSelect = (key, keyPath) => {
  activeIndex.value = key
}


</script>

<template>
    <div class="clothes-details">
<!--      商品的展示图片-->
      <div class="clothes-details-img">
        <el-carousel height="436px" motion-blur>
          <el-carousel-item v-for="(item,index) in headerImgs" :key="index">
            <el-image :src="item" fit="cover" style="height: 100%;width: 100%;"/>
          </el-carousel-item>
        </el-carousel>
      </div>
      <el-divider direction="vertical" style="height: 100%;min-height:436px;margin-left: 30px;margin-top: 30px;"/>
<!--      右边商品的各种筛选条件-->
      <div class="clothes-details-conditions">
        <p>{{product.name}}</p>

        <p class="user-address">
          <span>收货地址: &emsp;</span>
          <el-select
            v-model="selectAddress"
            clearable
            placeholder="请选择地址"
            style="width: 240px"
          >
            <el-option
              v-for="item in address"
              :key="item.id"
              :value="item.address"
            />
            <el-option value=""><el-link type="primary" href="/address">添加新地址</el-link></el-option>
          </el-select>
        </p>
        <p class="clothes-color" v-if="colors.length !== 0">
          <span>选择颜色: &emsp;</span>
          <el-radio-group v-model="select_color" size="large">
            <el-radio-button  v-for="item in colors" :key="item" :value="item">{{item}}</el-radio-button>
          </el-radio-group>
        </p>
        <p class="clothes-size">
          <span>{{getSize(product.type)}}: &emsp;</span>

            <el-radio-group v-model="selectSize" size="large" v-if="sizes.size !== 0">
              <el-radio-button  v-for="(item,index) in sizes.get(select_color)" :key="index" :value="item.get('size')" :disabled="item.get('stock') <= 0">{{item.get('size')}}</el-radio-button>
            </el-radio-group>
        </p>

        <p class="clothes-number">
            <span>数量: &emsp;</span>
            <el-input-number v-model="product_number" :min="1" style="text-align: center;" @change="productNumberChange"/>
        </p>

        <p class="clothes-buy">
          <el-button style="width: 200px;height: 50px;" size="large" @click="dialogVisible = true ">立即购买</el-button>
          <el-button style="width: 200px;height:50px;" size="large" v-if="shipping_cart" disabled>已经加入购物车</el-button>
          <el-button style="width: 200px;height:50px;" size="large" v-else @click="addToCart">加入购物车</el-button>
        </p>
      </div>
    </div>

  <div class="product_about">
    <el-menu  :default-active="activeIndex"
              class="el-menu-top"
              mode="horizontal"
              @select="handleSelect">
      <el-menu-item v-for="item in goods_page_bottom" :index="item.id.toString()" :key="item.id">
        {{item.name}}
      </el-menu-item>
    </el-menu>

    <el-main>
      <GoodsDetailsView v-if="activeIndex === '1'" :message="product.id"/>
      <SpecificationView v-if="activeIndex === '2'"/>
      <AfterSaleProtection v-if="activeIndex === '3'"/>
      <GoodsComment v-if="activeIndex === '4'"/>
      <ShopGoodGoods v-if="activeIndex === '5'"/>

    </el-main>

  </div>

  <el-dialog
    v-model="dialogVisible"
    header="支付提示"
    width="500"
  >
    <span>确认支付？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="buyNow">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

.clothes-details{
  position: relative;
  width: 1200px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
}

.clothes-details-img{
  margin-top: 30px;
  width: 439px;
  height: 436px;
}


.clothes-details-conditions{
  width: 500px;
  float: left;
  margin: 50px 0 0 60px;
}

.clothes-size,.user-address,.clothes-color,.clothes-buy{
  margin-top: 30px;
}

.clothes-number{
  margin-top: 30px;
}

.product_about{
  border: #99a9bf solid 1px;
  border-bottom: none;
  position: relative;
  width: 1200px;
  left: 50%;
  transform: translateX(-50%);
  top: 50px;
}
</style>